package com.cat.graphTheory;

import java.util.Arrays;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/description/
 * @create 2025/9/25 21:30
 * @since JDK17
 */

public class Solution36 {
    public int findTheCity(int n, int[][] edges, int distanceThreshold) {
        int[][] arr = new int[n][n];
        int min = Integer.MAX_VALUE, ans = -1;
        for (int i = 0; i < n; i++) {
            Arrays.fill(arr[i], Integer.MAX_VALUE);
            arr[i][i] = 0;
        }
        for (int[] e : edges) {
            arr[e[0]][e[1]] = e[2];
            arr[e[1]][e[0]] = e[2];
        }
        for (int h = 0; h < n; h++) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    if (arr[i][h] != Integer.MAX_VALUE && arr[h][j] != Integer.MAX_VALUE && arr[i][j] > arr[i][h] + arr[h][j]) {
                        arr[i][j] = arr[i][h] + arr[h][j];
                    }
                }
            }
        }
        for (int i = 0; i < n; i++) {
            int cnt = 0;
            for (int j = 0; j < n; j++) {
                if (arr[i][j] <= distanceThreshold) {
                    cnt++;
                }
            }
            if (cnt <= min) {
                ans = i;
                min = cnt;
            }
        }
        return ans;
    }
}
